package com.mantru.iotpot.dishes

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.DishesListAdapter
import com.mantru.iotpot.R
import com.mantru.iotpot.Util.MathUtil
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.databinding.ActivityDishesListBinding

class DishesListActivity : AppCompatActivity() {
    private val viewModel by viewModels<DishesListViewModel>()
    private lateinit var binding: ActivityDishesListBinding
    //adapter属于UI层，负责交互，留在Activity
    private var dishesListAdapter: DishesListAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_list)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()
        //观察网络请求结果
        observeVegetableExistsResult()
    }

    //初始化recyclerview
    private fun setRecyclerView(){
        dishesListAdapter = DishesListAdapter(this, R.layout.adapter_dishes_list, viewModel.dishesList.value ?: mutableListOf())
        binding.dishesListRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesListAdapter
        }
        //初始化要添加第一个item
        viewModel.addItem()
    }

    //设置控件交互事件
    private fun setContentAction(){
        //关闭按钮
        binding.back.setOnClickListener {
            finish()
        }

        //添加按钮
        binding.dishesListAdd.setOnClickListener {
            viewModel.addItem()
        }

        //adapter交互
        dishesListAdapter!!.setDishesListListener(object : DishesListAdapter.DishesListListener{
            override fun onDelete(position: Int) {
                //点击删除按钮，删除该项
                viewModel.deleteItem(position)
            }

            override fun setNum(position: Int, value: String) {
                //获取该项的份数
                if (viewModel.numList.get()?.contains(value) == true){
                    //Toast.makeText(this@DishesListActivity, "已存在该规格,请重新选择", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(this@DishesListActivity, "已存在该规格,请重新选择")
                    viewModel.numList.get()?.set(position, "")
                    dishesListAdapter!!.notifyItemChanged(position)
                    return
                }
                viewModel.numList.get()?.set(position, value)
            }

            override fun setWeight(position: Int, value: String) {
                //获取该项重量
                viewModel.weightList.get()?.set(position, MathUtil.trimLeadingZeros(value))
            }
        })

        //下一步按钮
        binding.dishesListButton.setOnClickListener{
            //先判断菜谱名称是否存在
            //后续处理结果在observeVegetableExistsResult()
            if ( viewModel.numList.get()!!.isNotEmpty() ){
                if ( viewModel.numList.get()!![0].isNotEmpty() ){
                    val map: MutableMap<String, Any> = HashMap()
                    map["vegetable_id"] = 0
                    map["vegetable_name"] = viewModel.dishName.get().toString()
                    map["copies_qty"] = viewModel.numList.get()!![0].replace("份", "").toInt()
                    viewModel.getHttpValue("GetSQLData_VegetableAndSpec_IsExists", map)
                } else {
                    ToastUtils.show(this@DishesListActivity, "请填入第1个规格的份数")
                }
            }

            // 获取输入法管理器
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
            imm?.hideSoftInputFromWindow(this@DishesListActivity.currentFocus?.windowToken, 0)
        }

        //监听输入框回车按键
        binding.dishName.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
            list?.let {
                dishesListAdapter?.updateData(it)
            }
        }
    }

    //观察网络请求结果
    private fun observeVegetableExistsResult() {
        viewModel.vegetableExistsResult.observe(this) { exists ->
            exists?.let {
                if (it) {
                    // 如果菜谱已存在
                    //Toast.makeText(this, "该菜谱名已存在，请重新输入", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(this, "该菜谱中份数为"+viewModel.numList.get()!![viewModel.askLength]+"的规格已存在，请重新输入")
                } else {
                    viewModel.askLength++
                    //如果还有规格没查询，则继续查询，否则跳转下一步
                    if ( viewModel.askLength < viewModel.numList.get()!!.size ){
                        if ( viewModel.numList.get()!![viewModel.askLength].isNotEmpty() ){
                            val map: MutableMap<String, Any> = HashMap()
                            map["vegetable_id"] = 0
                            map["vegetable_name"] = viewModel.dishName.get().toString()
                            map["copies_qty"] = viewModel.numList.get()!![viewModel.askLength].replace("份", "").toInt()
                            viewModel.getHttpValue("GetSQLData_VegetableAndSpec_IsExists", map)
                        } else {
                            ToastUtils.show(this@DishesListActivity, "请填入第"+viewModel.askLength+"个规格的份数")
                        }
                    } else {
                        // 如果菜谱不存在，继续执行跳转逻辑
                        if (viewModel.judgeNextOrNot()) {
                            //转换为字符串列表
                            val numListAsString = viewModel.numList.get().orEmpty().map { it }
                            val weightListAsString = viewModel.weightList.get().orEmpty().map { it }

                            val intent = Intent(this@DishesListActivity, DishesCreateActivity::class.java)
                            intent.putStringArrayListExtra("numList", ArrayList(numListAsString))
                            intent.putStringArrayListExtra("weightList", ArrayList(weightListAsString))
                            intent.putExtra("name", viewModel.dishName.get().toString())
                            startActivity(intent)
                            finish()
                        }
                    }
                }
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }
    }
}